/**
 * Copyright (c) 2015 XiaoYuanShenQi. All rights reserved.

 * Author: newma
 * Date: 7/4/15
 * Descript:

 *  Modified:
 */
var queryString = require('querystring');
var http = require('http');
var Log = require('./logger');
var clone = require('clone');

var Engine = function(options) {
    this.options = {
        host: 'localhost',
        port: 80
        //path: '/api'
    }

    if (options) {
        if (options.host != undefined) {
            this.options.host = options.host;
        }
        if (options.port != undefined) {
            this.options.port = options.port;
        }
        if (options.path != undefined) {
            this.options.path = options.path;
        }
    }
};

Engine.prototype.setOptions = function (options) {
    this.options = options;
};

Engine.prototype.__request = function (options, data, cb) {
    Log.debug(__filename + ' [Engine __request]: options - ' + JSON.stringify(options));
    var req = http.request(options, function(res) {
        res.setEncoding('utf8');

        var option = {
            json: true,
            statusCode: res.statusCode
        };

        var body = '';
        res.on('data', function (chunk) {
            body += chunk;
        });

        res.on('end', function() {
            var result;

            try {
                result = JSON.parse(body);
            } catch(err) {
                result = body;
                option.json = false;
            }

            cb(null, result, option);
        }.bind(this));
    }.bind(this));

    req.on('error', function(err) {
        cb(err, null);
    });

    if (data != null) {
        // write data to request body
        req.write(data);
    }

    req.end();
    //console.log('http request successfully!');
};

/**
 * http的post请求
 * @param data 要请求的参数对象，结构为 { ar1: val1, arg2: val2 ...... }
 * @param cb   function(err, result, opt) 如果有错误则err不为null；opt的结构为{ json: *true时为json对象，false时为字符串*, statusCode: *http返回的状态码* }
 */
Engine.prototype.post = function(data, cb) {
    var contentLength = 0;
    var postData = null;
    if (data) {
        postData = queryString.stringify(data);
        if (postData) {
            contentLength = postData.length;
        };
    }

    var options = clone(this.options);
    options.method = 'POST';
    options.headers = {
        'Content-Type':  'application/x-www-form-urlencoded',
        'Connection':    'keep-alive',
        'Response-Type': 'json',
        'Content-Length': contentLength
    };

    Log.debug(__filename + ' [Engine post]: post data - ' + postData);
    this.__request(options, postData, cb);
};

/**
 * http的get请求
 * @param data  要请求的参数对象，结构为 { ar1: val1, arg2: val2 ...... }
 * @param cb    function(err, result, opt) 如果有错误则err不为null；opt的结构为{ json: *true时为json对象，false时为字符串*, statusCode: *http返回的状态码* }
 */
Engine.prototype.get = function(data, cb) {
    var options = clone(this.options);
    options.method = 'GET';

    if (data != null) {
        var queryParam = queryString.stringify(data);
        if (queryParam != null && queryParam != '') {
            options.path += '?' + queryParam;
        }
    }

    this.__request(options, null, cb);
};

module.exports = Engine;
